package com.jeomo.shiro.endpoints;

import com.jeomo.common.core.result.CommonResult;
import com.jeomo.common.core.util.BeanCopyUtil;
import com.jeomo.shiro.bean.CustomizedUsernamePasswordToken;
import com.jeomo.shiro.dto.LoginInfo;
import com.jeomo.shiro.request.LoginRequest;
import com.jeomo.sys.api.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: qbt
 * @Date: 2020/7/26 22:12
 * @Version 1.0
 */
@RestController
@RequestMapping("/auth")
public class ShiroEndPoints {

    /**
     * 提示登录信息
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "请登录";
    }

    /**
     * 登录
     *
     * @param loginRequest 请求
     * @param platform     登录平台
     * @return
     */
    @PostMapping("/doLogin")
    public CommonResult<LoginInfo> doLogin(@RequestBody LoginRequest loginRequest, @RequestHeader(defaultValue = "MANAGE") String platform) {
        Subject subject = SecurityUtils.getSubject();
        CustomizedUsernamePasswordToken token = new CustomizedUsernamePasswordToken(loginRequest.getOrgCode(), loginRequest.getUsername(), loginRequest.getPassword(), platform);
        subject.login(token);
        LoginInfo loginInfo = (LoginInfo) (subject.getPrincipal());
        loginInfo.setToken(subject.getSession().getId().toString());

        return CommonResult.success(loginInfo);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping(value = "/logout")
    public CommonResult<Boolean> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return CommonResult.success(true);
    }

    /**
     * 登录成功
     *
     * @return
     */
    @RequestMapping("/success")
    public String authSuccess() {
        Subject subject = SecurityUtils.getSubject();
        return "(*´▽｀)ノノ，认证成功！欢迎您：" + subject;
    }

    /**
     * 认证失败
     *
     * @return
     */
    @RequestMapping("/error")
    public CommonResult<String> authError() {
        return CommonResult.failure("ε=(´ο｀*)))，认证失败！");
    }


    /**
     * 获取当前登录信息
     *
     * @return
     */
    @RequestMapping("/user/info")
    public CommonResult<UserVo> user() {
        Subject subject = SecurityUtils.getSubject();
        LoginInfo loginInfo = (LoginInfo) (subject.getPrincipal());
        return CommonResult.success(BeanCopyUtil.copyProperties(loginInfo.getLoginUser(), UserVo.class));
    }


}
